from fastapi import APIRouter, Body, HTTPException
from fastapi.responses import StreamingResponse

from .service import get_file_stream_and_cleanup, render_docx_template

router = APIRouter(prefix="/render", tags=["render"])


TEMPLATE_PATH = "public/template.docx"


@router.post("/")
async def render_template(template_id: str = Body(...), data: dict = Body(...)):
    try:
        tmp_file_path = render_docx_template(TEMPLATE_PATH, data)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except RuntimeError as e:
        raise HTTPException(status_code=500, detail=str(e))

    return StreamingResponse(
        get_file_stream_and_cleanup(tmp_file_path),
        media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        headers={
            "Content-Disposition": f"attachment; filename={template_id}_rendered.docx"
        },
    )
